<template>
  <div class="statistics_box">
    <el-row style="padding-bottom: 19px; border-bottom: 1px solid #ededed">
      <el-col class="l_p" :span="10">
        <span class="titles">接通率</span>
        <div class="bot">
          <el-progress
            :width="200"
            status="primary"
            type="dashboard"
            :stroke-width="20"
            :percentage="titleMap[2].num"
          >
            <template #default="{ percentage }">
              <span class="percentage-value">{{ percentage }}%</span>
            </template>
          </el-progress>
        </div>
      </el-col>
      <el-col :span="14" class="l_p2">
        <div class="radio_">
          <el-radio-group v-model="tabValue" size="small" @change="changeValue">
            <el-radio-button label="1">意向等级</el-radio-button>
            <el-radio-button label="2">交互次数</el-radio-button>
          </el-radio-group>
        </div>
        <Echart :height="300" ref="echartRef" :options="echartsOption" v-loading="loading" />
      </el-col>
    </el-row>
    <div class="status_box">
      <div class="title_">任务状态</div>
      <div class="status_ul">
        <div class="status_li" v-for="(item, index) in taskStatus" :key="index">
          <div class="flex items-center">
            <el-image
              style="width: 24px; height: 24px; margin-right: 8px"
              :src="imgUrl[item.name]"
            ></el-image>
            {{ item.name }}
          </div>
          <span class="txt" :class="className[item.name]">{{ item.value }}</span>
        </div>
        <div class="status_li" style="cursor: pointer" @click="showTx">
          <div class="flex items-center">
            <el-image style="width: 24px; height: 24px; margin-right: 8px" :src="m_wx"></el-image>
            已推微信数量
          </div>
          <span class="txt primary_">{{ titleMap[5].num || 0 }}</span>
        </div>
      </div>
    </div>
    <el-row style="padding: 19px 0; border-bottom: 1px solid #ededed">
      <el-col :span="10" style="border-right: 1px solid #ededed">
        <Echart :height="300" :options="topEchartsOption" v-loading="loading" />
      </el-col>
      <el-col :span="14">
        <Echart :height="300" :options="topEchartsOption2" v-loading="loading" />
      </el-col>
    </el-row>
    <div class="hour">
      <Echart :height="300" :options="topEchartsOption3" v-loading="loading" />
    </div>
    <div class="area">
      <Echart :height="400" :options="topEchartsOption4" v-loading="loading" />
    </div>
  </div>
  <WxTemplate ref="wxRefs" />
</template>

<script setup>
import * as WorkBenchApi from '@/api/call/workbench'
import china from '@/assets/map/json/china.json'
import echarts from '@/plugins/echarts'
import {
  countLevelByTask,
  countTalkByTask,
  facilitatorByTask,
  hourByTask,
  provincesByTask
} from '@/api/call/aiCall/index.ts'
import { cloneDeep } from 'lodash-es'
import * as TaskApi from '@/api/call/task'
import m_success from '@/assets/call/m_success.png'
import m_noCall from '@/assets/call/m_noCall.png'
import m_jj from '@/assets/call/m_jj.png'
import m_wx from '@/assets/call/m_wx.png'
import WxTemplate from './wxTemplate.vue'

echarts.registerMap('china', china)

const loading = ref(false)
const props = defineProps({
  activeItem: Object,
  statisticsTime: String
})
const queryParams = reactive({
  taskId: null,
  time: ''
})
const emit = defineEmits(['setNum'])
const imgUrl = {
  呼叫成功: m_success,
  坐席忙线未接听: m_jj,
  呼叫失败: m_noCall,
  已推微信数量: m_wx
}
const className = {
  呼叫成功: 'success_',
  坐席忙线未接听: 'primary_',
  呼叫失败: 'primary_',
  已推微信数量: 'primary_'
}
const topEchartsOption = reactive({
  title: {
    text: '时长统计',
    left: 'left',
    top: '3%',
    textStyle: {
      fontSize: 12,
      fontWeight: 'bold', // 字体粗细
      color: '#333' // 字体颜色
    }
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: '5%',
    left: 'center'
  },
  series: [
    {
      name: '通话时长',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
const topEchartsOption2 = reactive({
  title: {
    text: '运营商',
    left: '15px',
    top: '3%',
    textStyle: {
      fontSize: 12,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: '5%',
    left: 'center'
  },
  series: [
    {
      name: '运营商',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
const topEchartsOption3 = reactive({
  title: {
    text: '呼叫峰值',
    left: 'left',
    top: '3%',
    textStyle: {
      fontSize: 12,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    top: '10%',
    data: ['呼叫成功', '坐席忙线未接听', '呼叫失败']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    axisLabel: {
      rotate: 30, // 如果日期太长可以旋转30度
      interval: 0 // 强制显示所有标签
    }
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  series: [
    {
      name: '呼叫成功',
      type: 'bar',
      itemStyle: {
        color: '#67C23A', // 成功用绿色
        borderRadius: [5, 5, 0, 0]
      }
    },
    {
      name: '坐席忙线未接听',
      type: 'bar',
      itemStyle: {
        color: '#E6A23C', // 忙线用黄色
        borderRadius: [5, 5, 0, 0]
      }
    },
    {
      name: '呼叫失败',
      type: 'bar',
      itemStyle: {
        color: '#F56C6C', // 失败用红色
        borderRadius: [5, 5, 0, 0]
      }
    }
  ]
})
const topEchartsOption4 = reactive({
  title: {
    text: '地域分布',
    left: 'left',
    top: '3%',
    textStyle: {
      fontSize: 12,
      fontWeight: 'bold',
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'item',
    showDelay: 0,
    transitionDuration: 0.2
  },
  visualMap: {
    text: ['高', '低'],
    realtime: false,
    calculable: true,
    top: 'middle',
    inRange: {
      color: ['#fff', '#3b82f6']
    }
  },
  series: [
    {
      name: '地域分布',
      type: 'map',
      map: 'china',
      roam: false,
      selectedMode: false,
      data: []
    }
  ]
})
const titleMap = ref([
  {
    title: '外呼总数',
    name: 'totalCount',
    num: 0,
    id: 1,
    unit: '个'
  },
  {
    title: '接通总数',
    name: 'successCount',
    num: 0,
    id: 2,
    unit: '个'
  },
  {
    title: '接通率',
    name: 'successRate',
    num: 0,
    id: 3,
    unit: '%'
  },
  {
    title: '总通话时长',
    name: 'totalMinute',
    num: 0,
    id: 4,
    unit: '分钟'
  },
  {
    title: '平均通话时长',
    name: 'avgMinute',
    num: 0,
    id: 5,
    unit: '分钟'
  },
  {
    title: '已推微信数量',
    name: 'mpTemplateCount',
    num: 0,
    id: 6,
    unit: '个'
  }
])
const getList = async () => {
  let obj = cloneDeep(queryParams)
  if (!queryParams.time) {
    delete obj.time
  }
  const data = await WorkBenchApi.getWorkBench(obj)
  emit('setNum', data.mpTemplateCount)
  titleMap.value.forEach((item) => {
    if (data[item.name] !== undefined) {
      item.num = item.name == 'mpTemplateCount' ? data[item.name] : data[item.name].toFixed(2)
    }
  })
}
const tabValue = ref('1')
const echartRef = ref(null)
// 意向标签
const getCountLevelByTask = async () => {
  try {
    loading.value = true
    let obj = cloneDeep(queryParams)
    if (!queryParams.time) {
      delete obj.time
    }
    const data = await countLevelByTask(obj)
    let xAxisData = []
    let yAxisReceiveNumber = []
    data.map((item) => {
      xAxisData.push(item.name || '未知')
      yAxisReceiveNumber.push(item.value)
    })
    echartsOption.xAxis['data'] = xAxisData
    echartsOption.series[0]['data'] = yAxisReceiveNumber
  } finally {
    loading.value = false
  }
}

// 交互次数
const getCountTalkByTask = async () => {
  try {
    loading.value = true
    let obj = cloneDeep(queryParams)
    if (!queryParams.time) {
      delete obj.time
    }
    let xAxisData = []
    let yAxisReceiveNumber = []
    const data = await countTalkByTask(obj)
    data.map((item) => {
      xAxisData.push(item.name)
      yAxisReceiveNumber.push(item.value)
    })
    echartsOption.xAxis['data'] = xAxisData
    echartsOption.series[0]['data'] = yAxisReceiveNumber
  } finally {
    loading.value = false
  }
}
// 切换意向标签和交互次数
const changeValue = (val) => {
  if (val == '1') {
    getCountLevelByTask()
  } else {
    getCountTalkByTask()
  }
  if (echartRef.value && echartRef.value.chartInstance) {
    echartRef.value.chartInstance.setOption(echartsOption, true)
  }
}
const resultTypeMap = {
  1: '呼叫成功',
  95: '坐席忙线未接听',
  99: '呼叫失败'
}
const taskStatus = ref([])
// 状态
const getTaskStatus = async () => {
  const data = await TaskApi.getCountTask(queryParams.taskId)
  data.forEach((item) => {
    item.name = resultTypeMap[item.name]
  })
  const obj = cloneDeep(data)
  taskStatus.value = obj
}
/*获取时长统计*/
const getDurationStatistics = async () => {
  const data = await WorkBenchApi.getTimePieData(queryParams)
  const result = Object.entries(data).map(([name, value]) => ({ value, name }))
  topEchartsOption.series[0].data = result
}
/**运营商*/
const getFacilitatorByTask = async () => {
  let obj = cloneDeep(queryParams)
  if (!queryParams.time) {
    delete obj.time
  }
  topEchartsOption2.series[0].data = await facilitatorByTask(obj)
}
const processChartData = (rawData) => {
  const xAxisData = rawData.success.map((item) => item.name || '未知')

  // 创建映射表
  const successMap = new Map(rawData.success.map((item) => [item.name || '未知', item.value]))
  const leakMap = new Map(rawData.leak.map((item) => [item.name || '未知', item.value]))
  const failMap = new Map(rawData.fail.map((item) => [item.name || '未知', item.value]))

  // 填充数据（仅填充 xAxisData 中存在的点）
  const successData = xAxisData.map((time) => successMap.get(time) || 0)
  const leakData = xAxisData.map((time) => leakMap.get(time) || 0)
  const failData = xAxisData.map((time) => failMap.get(time) || 0)

  return {
    xAxisData: xAxisData,
    seriesData: [
      { name: '呼叫成功', data: successData },
      { name: '坐席忙线未接听', data: leakData },
      { name: '呼叫失败', data: failData }
    ]
  }
}
/*呼叫峰值*/
const getHourByTask = async () => {
  let obj = cloneDeep(queryParams)
  if (!queryParams.time) {
    delete obj.time
  }
  const data = await hourByTask(obj)
  const chartData = processChartData(data)
  topEchartsOption3.xAxis.data = chartData.xAxisData
  topEchartsOption3.series[0].data = chartData.seriesData[0].data
  topEchartsOption3.series[1].data = chartData.seriesData[1].data
  topEchartsOption3.series[2].data = chartData.seriesData[2].data
}
/**地域分布*/
const getProvincesByTask = async () => {
  let obj = cloneDeep(queryParams)
  if (!queryParams.time) {
    delete obj.time
  }
  const data = await provincesByTask(obj)
  let min = 0
  let max = 0
  topEchartsOption4.series[0].data = data.map((item) => {
    min = Math.min(min, item.value || 0)
    max = Math.max(max, item.value || 0)
    return { ...item }
  })
  topEchartsOption4.visualMap['min'] = min
  topEchartsOption4.visualMap['max'] = max
}
watch(
  () => [props.activeItem, props.statisticsTime],
  ([val, val2]) => {
    queryParams.time = val2
    if (val || val2) {
      queryParams.taskId = val.taskId
      getList()
      getTaskStatus()
      getDurationStatistics()
      getFacilitatorByTask()
      getHourByTask()
      getProvincesByTask()
      if (tabValue.value == '1') {
        getCountLevelByTask()
      } else {
        getCountTalkByTask()
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const echartsOption = reactive({
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'bar'
    }
  ]
})

const wxRefs = ref(null)
//已推微信数量详情
const showTx = () => {
  wxRefs.value.open(props.activeItem.taskId)
}
</script>

<style lang="scss" scoped>
.statistics_box {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 4px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
  &::-webkit-scrollbar-thumb {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:horizontal:start {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  &::-webkit-scrollbar-thumb:horizontal:end {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
}
.l_p {
  width: 100%;
  height: 300px;
  font-size: 12px;
  position: relative;
  text-align: center;
  border-right: 1px solid #ededed;
  .titles {
    position: absolute;
    color: #333;
    left: 20px;
    top: 20px;
  }
  .bot {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
.l_p2 {
  position: relative;
  .radio_ {
    position: absolute;
    top: 0;
    left: 20px;
    z-index: 9;
  }
}
.status_box {
  padding: 20px 0;
  font-size: 12px;
  border-bottom: 1px solid #ededed;
  .title_ {
    color: #333;
    height: 30px;
    line-height: 30px;
    margin-bottom: 18px;
  }
  .status_ul {
    display: flex;
    .status_li {
      width: 20%;
      background-color: #fcfdff;
      font-size: 14px;
      padding: 6px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .txt {
        font-size: 24px;
        font-weight: 700;
      }
      .success_ {
        color: #4cc288;
      }
      .primary_ {
        color: #5368a5;
      }
    }
  }
}
.hour {
  padding: 19px 0;
  border-bottom: 1px solid #ededed;
}
.area {
  padding: 19px 0;
}
</style>
